<?php

namespace app\common\model;

use app\common\service\UserShareImageService;
use think\Exception;
use think\Model;

class UserShareImage extends Model
{
    /**
     * build
     * @param $uid
     * @throws
     */
    public function build($appId, $uid)
    {
        // 检查是否已经生成
        $count = $this->where([['uid', '=', $uid]])->count();
        if ($count) {
            return;
        }

        // 生成邀请二维码
        $imageUrl = (new UserShareImageService())->create($appId, $uid);

        // 保存二维码
        $time = time();
        $saveData = [
            'uid' => $uid,
            'url' => $imageUrl,
            'create_time' => $time,
        ];
        $isInsert = $this->insert($saveData);
        if (!$isInsert) {
            throw new Exception('保存二维码失败');
        }
    }
}